package com.xhy.documents_collection.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhy.documents_collection.annotations.FileLog;
import com.xhy.documents_collection.enums.BusinessType;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.entity.PO.task.Task;
import com.xhy.documents_collection.entity.PO.task.TaskRecord;
import com.xhy.documents_collection.entity.PO.task.TaskUser;
import com.xhy.documents_collection.entity.PO.team.Team;
import com.xhy.documents_collection.annotations.Restriction;
import com.xhy.documents_collection.service.*;
import com.xhy.documents_collection.service.oss.OssService;
import com.xhy.documents_collection.service.task.TaskRecordService;
import com.xhy.documents_collection.service.task.TaskService;
import com.xhy.documents_collection.service.task.TaskUserService;
import com.xhy.documents_collection.service.team.TeamService;
import com.xhy.documents_collection.utils.R;
import com.xhy.documents_collection.utils.TransitionByteToCH;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Author: Xhy
 * CreateTime: 2022-11-21 11:15
 * 用户文件以及文件记录相关操作
 */

@RestController
@RequestMapping("/user/task")
public class UTaskController {

    @Resource
    private TaskService taskService;

    @Resource
    private TaskRecordService taskRecordService;


    @Resource
    private TeamService teamService;

    @Resource
    UserService userService;

    @Resource
    private TaskUserService taskUserService;

    @Resource
    private OssService ossService;

    // 查出用户的任务
    @GetMapping("/page")
    @Authority("user:task:page")
    public R recordPage(@RequestParam(value = "page") Long current,
                        @RequestParam(value = "limit") Long limit,
                        @RequestParam(required = false) String name
    ){
        Integer uId = UserHolder.get();
        // 获取任务id
        List<Integer> taskIds = taskUserService.list(new QueryWrapper<TaskUser>().eq("u_id", uId).select("t_id")).stream().map(TaskUser::getTId).collect(Collectors.toList());
        R r = R.ok();
        // 根据任务记录表查出taskId
        if (!ObjectUtils.isEmpty(taskIds)){
            Map<Integer, String> teamMap =teamService.list(new QueryWrapper<Team>().select("id", "name")).stream()
                    .collect(Collectors.toMap(Team::getId,Team::getName));

            Page<Task> page = taskService.page(new Page<>(current, limit), new LambdaQueryWrapper<Task>().in(Task::getId, taskIds)
                    .like(!ObjectUtils.isEmpty(name), Task::getName, name)
                    .orderByDesc(Task::getGmtCreated));
            // 填充 所属团队 提交状态
            Date date = new Date();
            for (Task task : page.getRecords()) {
                task.setTeamName(teamMap.get(task.getTId()));
                // 填充当前任务状态
                task.setTaskTimeState(date.compareTo(task.getEndTime()) == -1 ? true : false);
                task.setUrl("");
                task.setFilePath(new String(Base64.getEncoder().encode(task.getFilePath().getBytes())));
            }

            return r.data("data",page.getRecords()).count(page.getTotal());
        }
        return r;
    }



    /**
     * 查看任务详情 -> 提交记录表
     * @param current
     * @param limit
     * @param taskId
     * @return
     */
    @GetMapping("/get/{taskId}")
    @Authority("user:task:get")
    public R get(@RequestParam(value = "page") Long current,
                 @RequestParam(value = "limit") Long limit,
                 @PathVariable String taskId
                 ){
        Integer uId = UserHolder.get();
        Page<TaskRecord> page = taskRecordService.page(new Page<>(current, limit), new QueryWrapper<TaskRecord>()
                .eq("t_id", taskId)
                .eq("u_id",uId)
                .select("id", "u_id", "file_name", "file_size", "is_submit","submit_time","troop_id","file_path"));
        TaskRecord taskRecord = page.getRecords().get(0);
        taskRecord.setUserName(userService.getById(taskRecord.getUId()).getName());
        taskRecord.setFileSizeString(TransitionByteToCH.getPrintSize(taskRecord.getFileSize()));
        byte[] encode = Base64.getEncoder().encode(taskRecord.getFilePath().getBytes());
        taskRecord.setFilePath(new String(encode));
        return R.ok().data("data", page.getRecords()).count(page.getTotal());
    }

    // 上传
    @PostMapping("/upload")
    @Authority("user:task:upload")
    @Restriction(limit = 2,time = 3600)
    @FileLog(title = ServiceType.OSS,businessType = BusinessType.UPLOAD)
    public R upload(MultipartFile file, @RequestParam String taskRecordId){
        return ossService.userUpload(file,taskRecordId);
    }

    // 撤回
    @DeleteMapping("/sendBack/{taskRecordId}")
    @Authority("user:task:back")
    @Restriction(limit = 8,time = 3600)
    @FileLog(title = ServiceType.OSS,businessType = BusinessType.SEND_BACK)
    public R sendBack(@PathVariable String taskRecordId){
        return ossService.userSendBack(taskRecordId);
    }


    // 用户首页展示(查出未完成的作业)
    @GetMapping("/index")
    public R index(){
        return taskService.noSubmit();
    }
}
